package net.diaowen.dwsurvey.service.impl;



import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.common.service.BaseServiceImpl;
import net.diaowen.dwsurvey.dao.LotteryActivityDao;
import net.diaowen.dwsurvey.dao.LotteryPrizeStatusDao;
import net.diaowen.dwsurvey.entity.LotteryActivity;
import net.diaowen.dwsurvey.entity.LotteryPrize;
import net.diaowen.dwsurvey.entity.LotteryPrizeStatus;
import net.diaowen.dwsurvey.service.LotteryActivityManager;
import net.diaowen.dwsurvey.service.LotteryPrizeManager;
import net.diaowen.dwsurvey.service.LotteryUserManager;

@Service
public class LotteryActivityManagerImpl extends BaseServiceImpl<LotteryActivity, String> implements LotteryActivityManager {
	
	@Autowired
	private LotteryActivityDao lotteryActivityDao;
	
	@Autowired
	private AccountManager accountManager;
	
	@Autowired
	private LotteryPrizeManager lotteryPrizeManager;
	
	@Autowired
	private LotteryPrizeStatusDao lotteryPrizeStatusDao;
	
	@Autowired
	private LotteryUserManager lotteryUserManager;
	
	@Override
	public void setBaseDao() {
		this.baseDao=lotteryActivityDao;
		
	}

	@Override
	public Page<LotteryActivity> findPage(Page<LotteryActivity> page, LotteryActivity entity) {
		page.setOrderBy("createTime");
		page.setOrderDir("desc");
		List<Criterion> criterions=new ArrayList<Criterion>();
		return lotteryActivityDao.findPageList(page, criterions);
	}
	
	@Override
	public void save(LotteryActivity entity){
		try{
			User curUser = accountManager.getCurUser();
			String id = entity.getId();
			if(id==null || id.equals("")){
				entity.setId(null);
				entity.setCreateUser(curUser.getId());
				entity.setCreateTime(new Date());
				entity.setVisibility(1);
				lotteryActivityDao.save(entity);
			}else{
				LotteryActivity lt = lotteryActivityDao.get(id);
				lt.setDescription(entity.getDescription());
				lt.setStartTime(entity.getStartTime());
				lt.setEndTime(entity.getEndTime());
				lt.setName(entity.getName());
				lt.setUpdateUser(curUser.getId());
				lt.setUpdateTime(new Date());
				lotteryActivityDao.save(lt);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public String bindSurvey(String lotteryActivityId, String surveyId) {
		HashMap<String,String> resultMap = new HashMap<String,String>();
		//先看看选中的试卷是否已经被其他活动绑定
		LotteryActivity oActivity = getBySurveyId(surveyId);
		if (oActivity!=null && !oActivity.getId().equals(lotteryActivityId)) {
			// 不是一个活动
			resultMap.put("flag", "0");
			resultMap.put("value", oActivity.getName());
			return new JSONObject(resultMap).toString(); 
		}
		
    	LotteryActivity cActivity = get(lotteryActivityId);
    	String bindSurveyId = cActivity.getSurveyId();
    	//想要更换新的绑定试卷，先看看老绑定是否已经开始抽奖
    	//已经和其他试卷绑定了,并且已经开始
    	if (bindSurveyId != null && !bindSurveyId.equals(surveyId)) {
    		if (isStart(bindSurveyId)) {
    			resultMap.put("flag", "1");
    			return new JSONObject(resultMap).toString(); 
    		} else {
        		cActivity.setSurveyId(surveyId);
        		cActivity.setUpdateTime(new Date());
        		cActivity.setUpdateUser(accountManager.getCurUser().getId());
        		save(cActivity);
    			resultMap.put("flag", "2");
    			return new JSONObject(resultMap).toString(); 
    		}
    	} else {
    		cActivity.setSurveyId(surveyId);
    		cActivity.setUpdateTime(new Date());
    		cActivity.setUpdateUser(accountManager.getCurUser().getId());
    		save(cActivity);
			resultMap.put("flag", "2");
			return new JSONObject(resultMap).toString(); 
    	}
	}

	@Override
	public boolean isStart(String surveyId) {
		String hql = "select  count(*) from SurveyAnswer sa , LotteryUser lu where sa.id = lu.surveyAnswerId and  sa.surveyId=?";
		Long count = (Long) lotteryActivityDao.findUniObjs(hql, surveyId);
		if (count != null && count > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public LotteryActivity getBySurveyId(String surveyId) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("surveyId", surveyId));
		criterions.add(Restrictions.eq("visibility", 1));
		return lotteryActivityDao.findFirst(criterions);
	}

	@Override
	public boolean isRunning(String surveyId,String wxId) {
		//判断是否有绑定的活动
		LotteryActivity la = getBySurveyId(surveyId);
		if (la == null) 
			return false;
		//看看是否在开始和截至日期之内
		Date curr = new Date();
		if (curr.compareTo(la.getEndTime()) > 0 || curr.compareTo(la.getStartTime()) < 0 ) {
			return false;
		}
		//看看是否已经抽满了
		LotteryPrize lp = lotteryPrizeManager.getByActivityId(la.getId());
		List<Criterion> criterions1=new ArrayList<Criterion>();
		criterions1.add(Restrictions.eq("lotteryPrizeId", lp.getId()));
		LotteryPrizeStatus lps = lotteryPrizeStatusDao.findFirst(criterions1);
		if (lps.getCurPrizeNo() == lps.getTalPrizeNo()) {
			return false;
		}
		//看看次数是否够用
		Long lotteryCount = lotteryUserManager.getUserLotteryedTimes(surveyId,wxId);
		int restCount = (int) (lp.getPartTimes() - lotteryCount);
		if (restCount <= 0) {
			return false;
		}
		return true;
	}
}
